<?php

namespace app\admin\controller\shops;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\Shop;
use app\admin\model\Admin;
use app\common\model\Order;
use think\Loader;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Superplay extends Backend
{

    /**
     * Play模型对象
     * @var \app\admin\model\Play
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Play;
        $this->view->assign("isPayList", $this->model->getIsPayList());
        $this->view->assign("statusList", $this->model->getPlayStatusList());
        // $this->db2 = Db::connect(config('database.db2'));
        // 分发渠道
        $channel = Db::name('channel')->where(['status'=>1])->select();
        $this->view->assign("channel", $channel);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter = input('filter','');
            $decode = json_decode($filter,1);
            $where2 = '';
            if (isset($decode['channel']) && $decode['channel']) {
                $where2 .= ' and play.channel like "%'.$decode['channel'].'%"';
            }
            if (isset($decode['parent_play_no']) && $decode['parent_play_no']) {
                $where2 .= ' and play.channel like "%'.$decode['parent_play_no'].'%"';
            }
            if (isset($decode['end_time_str']) && $decode['end_time_str']) {
                $arr = explode(' - ', $decode['end_time_str']);
                $where2 .= ' and play.start_date='.strtotime($arr[0]).' and play.end_date='.strtotime($arr[1]);
            }
            if (isset($decode['play_type']) && $decode['play_type']) {
                if ($decode['play_type']==1) {
                    $where2 .= ' and play.play_type =1';
                } elseif($decode['play_type']==2) {
                    $where2 .= ' and play.play_type in (3,'.$decode['play_type'].')';
                }
            }
            if (isset($decode['phone']) && $decode['phone']) {
                $where2 .= ' and shop.phone like "%'.$decode['phone'].'%"';
            }
            if (isset($decode['shop.shop_name']) && $decode['shop.shop_name']) {
                $shop_no = Db::name('shop')->where('shop_name like "%'.$decode['shop.shop_name'].'%"')->value('group_concat(shop_no)');
                if ($shop_no) {
                    $where2 .= ' and play.shop_no in ('.$shop_no.')';
                } else {
                    $where2 .= ' and 1=2';
                }
            }

            $list = Db::name('play')->alias('play')
                ->field('play.*,user.nickname,shop.shop_name,shop.address,shop.phone')
                ->join('chbc_shop shop','play.shop_no=shop.shop_no','left')
                ->join('chbc_user user','play.user_id=user.id','left')
                ->where($where)
                ->where('play.super_play_no>0 and play.play_status>0'.$where2)
                ->order($sort, $order)
                ->paginate($limit);
            $list2 = $list->items();

            foreach ($list2 as &$row) {
                if ($row['channel']) {
                    $channel=json_decode($row['channel'],1);
                    $row['channel']='';
                    foreach ($channel as $key => $value) {
                        $row['channel'].='分发渠道：'.$value['channel_name'].'，';
                        $row['channel'].='名额：'.$value['quota'].'，';
                        if ($value['channel_status']=='未分发') {
                            $row['channel'].='状态：<span style="color:red;">'.$value['channel_status'].'</span>；</br>';
                        } elseif ($value['channel_status']=='已分发') {
                            $row['channel'].='状态：<span style="color:green;">'.$value['channel_status'].'</span>；</br>';
                        } elseif ($value['channel_status']=='无法分发') {
                            $row['channel'].='状态：<span style="color:orange;">'.$value['channel_status'].'</span>；</br>';
                        } else {
                            $row['channel'].='状态：'.$value['channel_status'].'；</br>';
                        }
                        $firstRelease = Db::name('play')->field('id')->where('channel like "%'.$value['channel_name'].'%" and shop_no='.$row['shop_no'])->order('id ASC')->find();
                        if ($firstRelease['id']==$row['id']) {
                            $row['channel'] = trim($row['channel'],'</br>');
                            $row['channel'].='<span style="color:blue;">首发；</span></br>';
                        }
                    }
                }
                $row['start_time_str'] = $row['start_time_str'].'~'.$row['end_time_str'];
                $row['stock_text'] = $this->model->getStockTextAttr($row['stock'],$row);
                $row['back_money_text'] = $this->model->getBackMoneyText2Attr($row['shop_settlement'],$row);
                $user = ['nickname' => $row['nickname']];
                $row['user'] = $user;
                $shop = ['shop_name' => $row['shop_name'],'address' => $row['address']];
                $row['shop'] = $shop;
                // 待上传
                $row['total_pay'] = Order::where(['play_no'=>$row['play_no'],'order_status'=>1])->count();
                // 待审核
                $row['total_service_amt'] = Order::where(['play_no'=>$row['play_no'],'order_status'=>2])->count();
                // 已完成
                $row['acture_pay'] = Order::where(['play_no'=>$row['play_no'],'order_status'=>3])->count();
                
                if ($row['pay_status']==0 && in_array($row['play_status'], [0,1,2,4])) {
                    $row['pay_status'] = '';
                }
                // 金额是商家实际要支付的，待支付状态才显示
                $row['total_money'] = '';
                if ($row['play_status']==3) {
                    $row['total_money'] = (float)Db::name('play_order')->where(['play_no'=>$row['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt+service_charge_amt)');
                }
                $row['user_id'] += config('virtual_userid');
                // 分发状态
                $row['parent_play_no'] = $row['channel'];
            }

            $result = array("total" => $list->total(), "rows" => $list2);

            return json($result);
        }
        $salesmanList = [];
        $salesman = $this->salesmanList();
        foreach ($salesman as $key => $value) {
            $salesmanList[$value['nickname']] = $value['nickname'];
        }
        // 分发渠道
        $channel = Db::name('channel')->where(['status'=>1])->select();
        foreach ($channel as $key => $value) {
            $channelList[$value['name']] = $value['name'];
        }
        $this->assignconfig(['salesmanList' => $salesmanList,'channelList'=>$channelList]);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                if (!isset($params['shop_no']) || !$params['shop_no']) $this->error('请选择正确的店铺');
                $shop = (new \app\admin\model\Shop())->where(['shop_no' => $params['shop_no'], 'shop_status' => 1])->find();
                if (empty($shop)) $this->error('该店铺暂不能发布活动');
                $user = (new \app\common\model\User())->where(['id' => $shop['have_uid'], 'user_type' => '1','status'=>'normal'])->find();
                if (empty($user)) $this->error('商家被封禁');
                if ($params['num'] <= 0) $this->error('活动名额有误');
                if (!isset($params['date_range']) || !$params['date_range']) $this->error('请选择日期范围');
                $date_range = explode(' - ', $params['date_range']);
                if (count($date_range)!=2) $this->error('日期范围有误');
                $params['start_date'] = strtotime($date_range[0]);
                $params['end_date'] = strtotime($date_range[1]);
                $params['user_id'] = $shop['have_uid'];
                if (strtotime($params['start_time_str']) >= strtotime($params['end_time_str'])) $this->error('请选择正确的活动时间');
                $params['img'] = $shop['logo_pic'];
                $params['shop_name'] = $shop['shop_name'];
                $params['shop_type'] = $shop['shop_type'];
                $params['middleman_id'] = $shop['middleman_id'];
                $params['play_status'] = 1;
                $params['stock'] = $params['num'];
                if ($params['shop_settlement'] <= $params['service_amt']) $this->error('请正确填写结算金额和技术服务费');
                $totalMoney = bcmul($params['user_pay'], $params['num'],2);
                $totalProcess = bcmul($params['service_amt'], $params['num'],2);
                $params['total_pay'] = $totalMoney;
                $params['total_service_amt'] = $totalProcess;
                $params['back_money'] = bcsub($params['shop_settlement'], $params['service_amt'],2);
                $params['total_money'] = bcadd(bcmul($params['back_money'], $params['num'],2), $totalProcess,2);
                $params['play_no'] = $this->generateNo(['biz_tag'=>'play_no','len'=>12,'int_prefix'=>2]);
                if (isset($params['is_loop']) && $params['is_loop']) {
                    $params['super_play_no'] = $this->generateNo(['biz_tag'=>'super_play_no','len'=>12,'int_prefix'=>3]);
                }
                $params['service_admin_id'] = $shop['salesman_admin_id'];
                $params['service_admin_by'] = strval(Admin::where('id',$shop['salesman_admin_id'])->value('nickname'));
                $params['create_by'] = $this->auth->nickname;
                $params['submit_admin_id'] = $this->auth->id;
                $params['play_status'] = 2;  // 后台添加的活动不用审核
                if ($params['play_label']>0) {
                    $params['virtual_num'] = mt_rand(0,5);
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $where['shop_status'] = ['=',1];
        $where['delete_dt'] = ['null',''];
        $shop = Shop::where($where)->field('id,shop_no,shop_name')->select();
        $this->view->assign("shop", $shop);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $time = time();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                // 分发渠道
                if (!isset($params['channel_id']) || !isset($params['quota'])) {
                    $this->error('请填写分发渠道信息');
                }
                if (count($params['channel_id'])!=count($params['quota'])) {
                    $this->error('分发渠道信息有误');
                }
                $channel = [];
                $quota = 0;
                foreach ($params['channel_id'] as $key => $value) {
                    if ($value=='吃喝不愁' && $params['quota'][$key]==0) $this->error($value.'渠道名额不能为0');
                    $channel[$key]['channel_id'] = Db::name('channel')->where('name',$value)->value('id');
                    if (!$channel[$key]['channel_id']) $this->error('未查询到渠道信息');
                    $channel[$key]['channel_name'] = $value;
                    $channel[$key]['quota'] = $params['quota'][$key];
                    $quota += $params['quota'][$key];
                    $channel[$key]['channel_status'] = $params['channel_status'][$key];
                    if ($channel[$key]['channel_name']=='吃喝不愁') {
                        $params['chbcquota'] = $channel[$key]['quota'];
                    }
                }
                if ($quota!=$params['num']) {
                    $this->error('分发总名额有误');
                }
                $params['channel'] = json_encode($channel,JSON_UNESCAPED_UNICODE);
                unset($params['channel_id']);
                unset($params['quota']);
                unset($params['channel_status']);

                // if (!isset($params['shop_no']) || !$params['shop_no']) $this->error('请选择正确的店铺');
                $shop = (new \app\admin\model\Shop())->where(['shop_no' => $row['shop_no'], 'shop_status' => 1])->find();
                if (empty($shop)) $this->error('该店铺暂不能发布活动');
                // $user = (new \app\common\model\User())->where(['id' => $shop['have_uid'], 'user_type' => '1','status'=>'normal'])->find();
                // if (empty($user)) $this->error('商家被封禁');
                if ($params['num'] <= 0) $this->error('活动名额有误');
                if ($params['play_type']==2 && !isset($params['is_qcsc'])) {
                    $this->error('请选择返利餐的显示位置');
                }
                // if ($params['play_type']==2 && $params['user_pay']!=0) {
                //     $this->error('返利餐用户实付金额为0');
                // }
                if (!isset($params['date_range']) || !$params['date_range']) $this->error('请选择日期范围');
                $date_range = explode(' - ', $params['date_range']);
                if (count($date_range)!=2) $this->error('日期范围有误');
                $params['start_date'] = strtotime($date_range[0]);
                $params['end_date'] = strtotime($date_range[1]);
                // if ($params['end_date']-$params['start_date']>86400) {
                //     $this->error('活动日期有误');
                // }
                $params['user_id'] = $shop['have_uid'];
                if (strtotime($params['start_time_str']) >= strtotime($params['end_time_str'])) $this->error('请选择正确的活动时间');
                $params['img'] = $shop['logo_pic'];
                $params['shop_name'] = $shop['shop_name'];
                $params['shop_type'] = $shop['shop_type'];
                $params['service_amt'] = $shop['service_amt'];
                $params['middleman_id'] = $shop['middleman_id'];
                // $params['play_status'] = 1;
                $params['stock'] = $params['num']-($row['num']-$row['stock']);
                // if ($params['shop_settlement'] <= $params['service_amt']) $this->error('请正确填写结算金额和技术服务费');
                $totalMoney = bcmul($row['user_pay'], $params['num'],2);
                $totalProcess = bcmul($shop['service_amt'], $params['num'],2);
                $params['total_pay'] = $totalMoney;
                $params['total_service_amt'] = $totalProcess;
                $params['back_money'] = bcsub($row['shop_settlement'], $shop['service_amt'],2);
                $params['total_money'] = bcadd(bcmul($params['back_money'], $params['num'],2), $totalProcess,2);
                $params['acture_total_money'] = $params['total_money'];
                // $params['play_no'] = $this->generateNo(['biz_tag'=>'play_no','len'=>12,'int_prefix'=>2]);
                // if (!$row['super_play_no'] && isset($params['is_loop']) && $params['is_loop']) {
                //     $params['super_play_no'] = $this->generateNo(['biz_tag'=>'super_play_no','len'=>12,'int_prefix'=>3]);
                // }
                $params['service_admin_id'] = $shop['salesman_admin_id'];
                $params['service_admin_by'] = strval(Admin::where('id',$shop['salesman_admin_id'])->value('nickname'));
                $params['update_by'] = $this->auth->nickname;
                // $params['submit_admin_id'] = $this->auth->id;

                if (isset($params['is_qcsc']) && $params['is_qcsc']==1 && $params['play_type']==2) {
                    $params['play_type']=3;
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    // 更新当日的普通活动
                    $today_start = strtotime(date('Ymd',$time));
                    $today_end = strtotime(date('Ymd',$time))+86399;
                    $model = new \app\admin\model\Play;
                    $play = $model->where(['parent_play_no'=>$row['super_play_no'],'start_date'=>$today_start,'end_date'=>$today_end])->find();
                    if ($play) {
                        unset($params['start_date']);
                        unset($params['end_date']);
                        $result = $play->allowField(true)->save($params);
                        // 渠道
                        Db::name('play_channel')->where('play_id',$play['id'])->update(['status'=>0]);
                        foreach ($channel as &$channels) {
                            $channels['play_id'] = $play['id'];
                            unset($channels['channel_name']);
                            unset($channels['channel_status']);
                        }
                        Db::name('play_channel')->insertAll($channel);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $rows = $row;
        $rows['date_range'] = date('Y-m-d H:i:s',$rows['start_date']).' - '.date('Y-m-d H:i:s',$rows['end_date']);
        $where['shop_status'] = ['=',1];
        $where['delete_dt'] = ['null',''];
        // $shop = Db::name('shop')->where($where)->field('id,shop_no,shop_name,shop_type')->select();
        // foreach ($shop as $key => &$value) {
        //     if ($value['shop_type']==1) {
        //         $value['shop_name'] = '【美团】'.$value['shop_name'];
        //     } else {
        //         $value['shop_name'] = '【饿了么】'.$value['shop_name'];
        //     }
        // }
        $nopay = Db::name('play_order')->where(['shop_no'=>$row['shop_no'],'order_status'=>['in',[3,6,-9]],'is_pay'=>0])->value('sum(actual_rebate_amt+service_charge_amt)');
        $shops = Db::name('shop')->where(['shop_no'=>$rows['shop_no']])->find();
        $business_time = json_decode($shops['business_time'],1);
        // 店铺服务费
        $shop_serviceamt = Db::name('shop_serviceamt')->where(['shop_no'=>$row->shop_no,'status'=>1])->select();
        $qrcode_pic = Db::name('shop_platform')->where('shop_no',$shops['shop_no'])->value('qrcode_pic');
        $qrcode = explode(',', $qrcode_pic);
        foreach ($qrcode as &$qr) {
            if (strpos($qr,'://')===false) {
                $qr = config('upload_domain').$qr;
            }
        }
        $data = [
            'nopay' => (float)$nopay,
            'address' => $shops['address'],
            'shop_type' => config('platform')[$shops['shop_type']],
            'qrcode' => $qrcode,
            'domain' => config('upload_domain'),
            'shop_name' => $rows['shop_name'],
            'startstr' => $business_time[0]['start'],
            'endstr' => $business_time[0]['end'],
            'service_amt' => $shops['service_amt'],
            'shop_serviceamt' => json_encode($shop_serviceamt,JSON_UNESCAPED_UNICODE),
        ];
        $this->view->assign("data", $data);
        $rowschannel = $rows['channel'] = json_decode($rows['channel'],1);
        foreach ($rowschannel as $key => &$value) {
            $value['mf'] = '';
            foreach ($shop_serviceamt as $k => $v) {
                if ($v['channel_name']==$value['channel_name']) {
                    $value['mf'] = '满'.intval($row['user_pay']).'返'.floatval($row['shop_settlement']-$v['service_amt']);
                }
            }
            $firstRelease = Db::name('play')->field('id')->where('channel like "%'.$value['channel_name'].'%" and shop_no='.$row['shop_no'])->order('id ASC')->find();
            $value['firstRelease'] = 1;
            if ($firstRelease['id']==$row['id']) {
                $value['firstRelease'] = 0;
            }
        }
        $rows['channel'] = $rowschannel;
        $this->view->assign("row", $rows);
        // 分发渠道
        $channel = Db::name('channel')->where(['status'=>1])->select();
        foreach ($channel as $key => &$value) {
            $value['firstRelease'] = Db::name('play')->where('channel like "%'.$value['name'].'%" and shop_no='.$rows['shop_no'])->count();
        }
        $this->view->assign("channel", $channel);
        return $this->view->fetch();
    }

    public function settle($ids = null)
    {
        $goods = $this->model->get($ids);
        if (!$goods) {
            $this->error(__('No Results were found'));
        }
        $goodsService = new \app\sapi\service\Play();
        if (empty($goods)) $this->error('商品不存在');
        if (in_array($goods['status'], [-1, -2]) || time() > $goods['end_time'])
            $this->success('结算成功', $goods);
        if ($goods['is_show'] == 0) {
            if (in_array($goods['status'], [0, 1])) {
                /* $goods->status == -1;
                 $goods->save();*/
            }
        } else {
            if ($goods['is_pay'] == 0) {
                $goods->status = -1;
                $goods->is_settle = 1;
                $goods->save();
            } else {
                $business = (new \app\common\model\Business())->where('id', $goods->business_id)->find();
                $res = $goodsService->settle($goods, $business);
                if (!$res) $this->error('结算失败', $goods);
            }
        }
        $this->success('结算成功', $goods);
    }
    
    /**
     * 同意
     */
    public function agree($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($row['play_status'] != 1) {
            $this->error(__('请不要重复审核！'));
        }
        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }
                // 审核通过
                $result = $row->allowField(true)->save([
                    'play_status' => 2,
                    'approve_by' => $this->auth->nickname,
                    'approve_time' => date('Y-m-d H:i:s'),
                    'update_by' => $this->auth->nickname,
                ]);
                $time = time();
                $today_start = strtotime(date('Ymd',$time));
                $today_end = strtotime(date('Ymd',$time))+86399;
                // 是否已经生成
                if (!Db::name('play')->where(['parent_play_no'=>$row['super_play_no'],'start_date'=>$today_start,'end_date'=>$today_end])->count()) {
                    $play_no = $this->generateNo(['biz_tag'=>'play_no','len'=>12,'int_prefix'=>2]);
                    $all = [];
                    $all['play_no'] = $play_no;
                    $all['user_id'] = $row['user_id'];
                    $all['shop_no'] = $row['shop_no'];
                    $all['shop_name'] = $row['shop_name'];
                    $all['play_type'] = $row['play_type'];
                    $all['start_date'] = $today_start;
                    $all['end_date'] = $today_end;
                    $all['start_time_str'] = $row['start_time_str'];
                    $all['end_time_str'] = $row['end_time_str'];
                    $all['scheme_no'] = $row['scheme_no'];
                    $all['service_amt'] = $row['service_amt'];
                    $all['service_admin_id'] = $row['service_admin_id'];
                    $all['service_admin_by'] = $row['service_admin_by'];
                    $all['deal_content'] = $row['deal_content'];
                    $all['play_status'] = 2;
                    $all['pay_status'] = 0;
                    $all['last_pay_time'] = 0;
                    $all['acture_pay'] = 0;
                    $all['order_over_num'] = 0;
                    $all['submit_uid'] = $row['submit_uid'];
                    $all['submit_admin_id'] = $row['submit_admin_id'];
                    $all['create_by'] = $row['create_by'];
                    $all['update_by'] = $row['update_by'];
                    $all['user_pay'] = $row['user_pay'];
                    $all['shop_settlement'] = $row['shop_settlement'];
                    $all['num'] = $row['num'];
                    $all['machine_audit'] = $row['machine_audit'];
                    $all['remarks'] = $row['remarks'];
                    $all['img'] = $row['img'];
                    $all['total_pay'] = $row['total_pay'];
                    $all['total_service_amt'] = $row['total_service_amt'];
                    $all['total_money'] = $row['total_money'];
                    $all['acture_total_money'] = $row['total_money'];
                    $all['is_pay'] = $row['is_pay'];
                    $all['back_money'] = $row['back_money'];
                    $all['play_label'] = $row['play_label'];
                    $all['shop_type'] = $row['shop_type'];
                    $all['stock'] = $row['num'];
                    $all['pay_type'] = $row['pay_type'];
                    $all['approve_by'] = $row['approve_by'];
                    $all['approve_time'] = $row['approve_time'];
                    $all['reject_content'] = $row['reject_content'];
                    $all['parent_play_no'] = $row['super_play_no'];
                    Db::name('play')->insertGetId($all);
                } else {
                    Db::name('play')->where(['parent_play_no'=>$row['super_play_no'],'start_date'=>$today_start,'end_date'=>$today_end])->update(['play_status'=>2,'pay_status'=>3,'update_by'=>$this->auth->id,'update_dt'=>date('Y-m-d H:i:s')]);
                }
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    
    /**
     * 拒绝
     */
    public function refuse($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    if ($row['play_status'] != 1) {
                        $this->error(__('请不要重复审核！'));
                    }
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['play_status'] = 6;
                    $params['approve_time'] = date('Y-m-d H:i:s');
                    $params['approve_by'] = $this->auth->nickname;
                    $params['update_by'] = $this->auth->nickname;
                    $result = $row->allowField(true)->save($params);
                    // 冻结金额返回
                    $User = new \app\common\model\User();
                    $money = -1*$row['acture_pay'];
                    $User->money($money, $row['user_id'], '冻结返还', $row['play_no'], 1);
                    // 余额增加
                    $User->money($row['acture_pay'], $row['user_id'], '冻结返还', $row['play_no']);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 结束活动
     * @DateTime 2023-04-30T22:59:00+0800
     * @return   [type]                   [description]
     */
    public function end($ids = null)
    {
        if (!$ids) {
            $this->error('缺少参数');
        }
        $row = $this->model->get($ids);
        if (!$row) $this->error('未查询到相关数据');
        Db::startTrans();
        try {
            // 前台发布活动提前取消的情况，把没有循环的活动冻结金额返还
            if ($row['pay_status']==3 && $row['is_pay']==1) {
                // 剩余天数
                $days = ($row['end_date']-(strtotime(date('Ymd'))+86400))/86400;
                if ($days>0) {
                    $money = -1*$days*$row['total_money'];
                    (new \app\common\model\User())->money($money, $row['user_id'], '冻结返还', $row['play_no'], 1);
                    $money = -1*$money;
                    (new \app\common\model\User())->money($money, $row['user_id'], '冻结返还', $row['play_no']);
                }
            }
            $row->play_status=4;
            $row->update_by=$this->auth->id;
            $row->pay_status=2;
            $row->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('失败');
        }
        $this->success();
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        
        // 状态参数过滤掉
        if (isset($filter['end_time_str'])) {
            unset($filter['end_time_str']);
        }
        if (isset($filter['play_type'])) {
            unset($filter['play_type']);
        }
        if (isset($filter['channel'])) {
            unset($filter['channel']);
        }
        if (isset($filter['phone'])) {
            unset($filter['phone']);
        }
        if (isset($filter['parent_play_no'])) {
            unset($filter['parent_play_no']);
        }
        if (isset($filter['user_id'])) {
            $filter['user_id'] = $filter['user_id']-config('virtual_userid');
        }
        if (isset($filter['shop.shop_name'])) {
            unset($filter['shop.shop_name']);
        }
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function($v){
                        return $v != '' && $v !== false && $v !== null;
                    })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }

}
